package com.bjc.platform.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bjc.platform.util.JSONHelper;
import com.bjc.platform.util.JSONResult;

public class VerificationCodeFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		String kaptchaExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		String randcode = request.getParameter("j_randcode");

		Map<String, String> status = new HashMap<String, String>();
		if (kaptchaExpected == null || !kaptchaExpected.equals(randcode)) {
			status.put("status", "INVALID_RAND_CODE");
			JSONResult json = new JSONResult(false, status);
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			try {
				response.getWriter().println(JSONHelper.map2json(json.getJSONResult()));
			} catch (Exception e) {
				e.printStackTrace();
			}
			response.flushBuffer();
		} else {
			arg2.doFilter(request, response);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
	}

}
